package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.exception.NullParamsException;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.SetmealService;
import com.sky.vo.SetmealVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin/setmeal")
@Slf4j
@Api(tags = "套餐相关接口")
public class SetMealController {

    @Autowired
    private SetmealService setmealService;

    @ApiOperation("套餐分页查询")
    @GetMapping("/page")
    public Result<PageResult> pageQuery (SetmealPageQueryDTO pageQueryDTO) {
        log.info("套餐分页查询:{}",pageQueryDTO);
        PageResult pageResult = setmealService.pageQuery(pageQueryDTO);
        return Result.success(pageResult);
    }

    @PutMapping
    @ApiOperation("修改套餐信息")
    @CacheEvict(cacheNames = "setmealCache",allEntries = true)
    public Result updateSetmeal (@RequestBody SetmealDTO setmealDTO) {
        log.info("修改套餐信息：{}",setmealDTO);
        setmealService.updateSetmeal(setmealDTO);
        return Result.success();
    }

    /**
     * 根据id查询套餐
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("根据id查询套餐")
    public Result<SetmealVO> querySetmealById (@PathVariable Long id) {
        log.info("根据id查询套餐:{}",id);
        SetmealVO setmealVO = setmealService.querySetmealById(id);
        return Result.success(setmealVO);
    }

    @ApiOperation("启用/禁用套餐")
    @PostMapping("/status/{status}")
    @CacheEvict(cacheNames = "setmealCache",allEntries = true)
    public Result changeStatus (@PathVariable Integer status, Long id) {
        log.info("修改套餐状态:{},{}",status,id);
        setmealService.changeStatus(status,id);
        return Result.success();
    }

    @PostMapping
    @ApiOperation("新增套餐")
    // 清理缓存，精确清理，新增只影响一份缓存数据
    @CacheEvict(cacheNames = "setmealCache",key = "#setmealDTO.categoryId")
    public Result insertSetmeal(@RequestBody SetmealDTO setmealDTO){
        log.info("新增套餐:{}",setmealDTO);
        setmealService.insertSetmeal(setmealDTO);
        return Result.success();
    }

    /**
     * 批量删除套餐
     * @return
     */
    @ApiOperation("批量删除套餐")
    @DeleteMapping
    // 不好算categoryId，直接把缓存全部清除
    @CacheEvict(cacheNames = "setmealCache",allEntries = true)
    public Result deleteSetmeals (@RequestParam List<Long> ids) {
        log.info("批量删除套餐:{}",ids);
        if(ids == null || ids.size() == 0){
            throw new NullParamsException(MessageConstant.EXIT_NULL_DATA);
        }
        setmealService.deleteSetmealsByIds(ids);
        return Result.success();
    }

}
